package cn.bgs.service.impl;

import cn.bgs.common.Constants;
import cn.bgs.dao.StuMapper;
import cn.bgs.entity.StuDTO;
import cn.bgs.entity.Student;
import cn.bgs.exception.ServiceException;
import cn.bgs.service.StuService;
import cn.bgs.utils.TokenUtils;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class StuServiceImpl extends ServiceImpl<StuMapper, Student> implements StuService {

    private static final Log LOG = Log.get();
    public Boolean saveAn(Student student) {
        return saveOrUpdate(student);
    }


    @Override
    public StuDTO login(StuDTO stuDTO) {

        // 处理异常情况
        Student one = getStulInfo(stuDTO);
        if(one!=null){
            BeanUtil.copyProperties(one,stuDTO,true);
            // 设置token
            String token = TokenUtils.genToken(one.getStuId().toString(), one.getPassword());
            stuDTO.setToken(token);

            return  stuDTO;
        }else {
            throw  new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }

    }

    @Override
    public Student register(StuDTO stuDTO) {
        Student one = getStulInfo(stuDTO) ;
        if(one==null){
            one=new Student();
            BeanUtil.copyProperties(stuDTO,one,true);
            save(one);
        }else {
            throw  new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }
        return  one;
    }

    private  Student getStulInfo(StuDTO stuDTO){

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", stuDTO.getEmail());
        queryWrapper.eq("password", stuDTO.getPassword());
        Student one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }
}
